<template>
  <div class="app-container">
    <div class="head-container" style="display: flex;gap: 10px;">
      <el-card style="flex: 3;">
        <!-- TODO: 字段增加及其查询 -->
        <div style="display: flex;align-items: flex-end;gap: 20px;">
          <div style="flex: 10;flex-direction: column;gap: 10px;">
            <el-row :gutter="10">
              <el-col :span="8" style="display: flex;justify-content: space-between;">
                <label class="el-form-item-label">料号</label>
                <el-input v-model.trim="query.productNo" clearable placeholder="料号" style="width: 8vw;" class="filter-item" @keyup.enter.native="toQuery" @clear="toQuery" />
              </el-col>
              <el-col :span="8" style="display: flex;justify-content: space-between;">
                <label class="el-form-item-label">母托编码</label>
                <el-input v-model.trim="query.parentPalletCode" clearable placeholder="母托编码" style="width: 8vw;" class="filter-item" @keyup.enter.native="toQuery" @clear="toQuery" />
              </el-col>
              <el-col :span="8" style="display: flex;justify-content: space-between;">
                <label class="el-form-item-label">物料描述</label>
                <el-input v-model="query.productDescription" clearable placeholder="物料描述" style="width: 8vw;" class="filter-item" @keyup.enter.native="toQuery" @clear="toQuery" />
              </el-col>
            </el-row>
            <el-row v-if="showQuery" :gutter="10">
              <el-col :span="8" style="display: flex;justify-content: space-between;">
                <label class="el-form-item-label">物料批次号</label>
                <el-input v-model.trim="query.batchCode" clearable placeholder="物料批次号" style="width: 8vw;" class="filter-item" @keyup.enter.native="toQuery" @clear="toQuery" />
              </el-col>
              <el-col :span="8" style="display: flex;justify-content: space-between;">
                <label class="el-form-item-label">良品/不良品</label>
                <el-select v-model="query.quality" style="width: 8vw;" class="filter-item" clearable placeholder="请选择" @change="toQuery">
                  <el-option
                    v-for="item in dict.production_quality"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-col>
              <el-col :span="8" style="display: flex;justify-content: space-between;">
                <label class="el-form-item-label">母托类型</label>
                <el-select v-model="query.parentPalletType" style="width: 8vw;" class="filter-item" clearable placeholder="请选择" @change="toQuery">
                  <el-option
                    v-for="item in dict.parentPallet_Type"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-col>
            </el-row>
            <el-row v-if="showQuery" :gutter="10">
              <el-col :span="8" style="display: flex;justify-content: space-between;">
                <label class="el-form-item-label">库区</label>
                <el-select v-model.trim="query.wareHouseType" style="width: 8vw;" class="filter-item" clearable placeholder="请选择" @change="toQuery">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.text"
                    :value="item.value"
                  />
                </el-select>
              </el-col>
            </el-row>
          </div>
          <div style="flex: 3;display: flex;align-items: center;">
            <el-button class="filter-item" size="mini" type="success" icon="el-icon-search" @click="toQuery">搜索</el-button>
            <el-button class="filter-item" size="mini" type="warning" icon="el-icon-refresh-right" @click="reset">重置</el-button>
            <span class="el-dropdown-link" @click="handlerClick">
              {{ showQuery ? '收起' : '更多查询' }}
              <i
                class="el-icon-arrow-down el-icon--right arrow-icon"
                :style="{ transform: showQuery ? 'rotate(180deg)' : 'rotate(0deg)' }"
              />
            </span>
          </div>
        </div>
        <el-table
          ref="table"
          v-loading="loading"
          :data="list"
          border
          :row-class-name="tableRowClassName"
          :span-method="objectSpanMethod"
          :cell-style="tableCellstyle"
          @select="handlerChange"
          @select-all="handlerAll"
          @selection-change="updateSelect"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="parentPalletCode" label="母托编码" />
          <el-table-column prop="parentPalletType" label="母托类型" width="70px">
            <template slot-scope="scope">
              {{ dict.label.parentPallet_Type[scope.row.parentPalletType] }}
            </template>
          </el-table-column>
          <el-table-column prop="lockStatus" label="储位状态" width="70px">
            <template slot-scope="scope">
              {{ dict.label.storage_lockStatus[scope.row.lockStatus] }}
            </template>
          </el-table-column>
          <el-table-column prop="storageCode" label="储位编码" />
          <el-table-column prop="storageType" label="储位类型">
            <template slot-scope="scope">
              {{ dict.label.storage_type[scope.row.storageType] }}
            </template>
          </el-table-column>
          <el-table-column prop="productNo" label="料号" />
          <el-table-column prop="productDescription" label="物料描述" />
          <el-table-column prop="qty" label="总数量" width="60px" />
          <el-table-column prop="nb" label="箱数" width="60px" />
          <el-table-column prop="quality" label="品质" width="60px">
            <template slot-scope="scope">
              {{ dict.label.production_quality[scope.row.quality] }}
            </template>
          </el-table-column>
          <el-table-column prop="creationDate" label="生产日期" />
        </el-table>
        <el-pagination
          style="margin-top: 10px;"
          :current-page.sync="query.current"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="query.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalElements"
          @size-change="handlerSizeChange"
          @current-change="handlerCurrentChange"
        />
      </el-card>
      <el-card style="flex: 1;">
        <div slot="header" style="display: flex;flex-direction: column;gap: 5px;">
          <div style="display: flex;justify-content: space-between;align-items: center;">
            <label style="margin-left: 5px;">已勾选母托</label>
            <el-button size="mini" :loading="btn.createBtn" type="primary" @click="createReturnOrder">创建移库单</el-button>
          </div>
          <div style="display: flex;flex-direction: column;gap: 0px;">
            <div style="display: flex;width: 70%;">
              <label class="el-form-item-label" style="flex: 1;text-align: left;">移库单类型</label>
              <el-select v-model="user.type" style="flex: 2;" class="filter-item" clearable placeholder="请选择">
                <el-option
                  v-for="item in dict.moveOrder_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.label === '退库回产线PT11' || item.label === '容器移库'"
                />
              </el-select>
            </div>
            <div style="display: flex;width: 70%;">
              <label class="el-form-item-label" style="flex: 1;text-align: left;">移库库区</label>
              <el-select v-model="user.warehouse" style="flex: 2;" class="filter-item" clearable placeholder="请选择">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.text"
                  :value="item.value"
                  :disabled="item.value === 'PT11' || user.type === '3'"
                />
              </el-select>
            </div>
          </div>
        </div>
        <el-table
          ref="selctTable"
          :data="select_table"
        >
          <el-table-column prop="parentPalletCode" label="母托" />
          <el-table-column label="操作" width="100px">
            <template slot-scope="scope">
              <el-button type="danger" @click="del(scope.row, scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getListAPI, createMoveOrderAPI } from '@/api/work/returnStock'
import { getWareHouseAPI } from '@/api/work/moveStorage'
export default {
  name: 'MoveStorage',
  dicts: ['moveOrder_type', 'parentPallet_Type', 'storage_type', 'production_quality', 'storage_lockStatus'],
  data() {
    return {
      query: {
        parentPalletCode: '',
        productDescription: '',
        productNo: '',
        batchCode: '',
        quality: '',
        parentPalletType: '',
        wareHouseType: '',
        current: 1,
        size: 10
      },
      loading: false,
      list: [],
      totalElements: 0,
      select_table: [],
      user: {
        type: '',
        warehouse: '',
        code: '',
        name: ''
      },
      options: [],
      btn: {
        createBtn: false
      },
      cellList: '',
      count: '',
      rowspanValue: '',
      showQuery: false
    }
  },
  mounted() {
    this.toQuery()
    this.getWareHouse()
  },
  methods: {
    tableRowClassName({ row, rowIndex }) {
      // console.log(row.quality)
      if (row.quality === 2) {
        // console.log(row.quality)
        return 'warning-row'
      } else {
        return ''
      }
    },
    tableCellstyle({ row, rowIndex }) {
      if (row.quality === 2) {
        return 'background:  #f3deb6'
      }
      return ''
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (column.property === 'parentPalletCode' || column.property === undefined) {
        // console.log(rowIndex)
        // console.log(row)
        if (rowIndex > 0 && row.parentPalletCode === this.list[rowIndex - 1].parentPalletCode) {
          return {
            rowspan: 0, // 与上一行相同的parentPalletCode，设置跨行数为0，即不显示
            colspan: 1 // 不进行跨列
          }
        }
        // 查找后续行是否与当前行的parentPalletCode相同
        let rowspan = 1
        for (let i = rowIndex + 1; i < this.list.length; i++) {
          if (this.list[i].parentPalletCode === row.parentPalletCode) {
            rowspan++
          } else {
            break
          }
        }
        return {
          rowspan: rowspan, // 跨行数为相同parentPalletCode的行数
          colspan: 1 // 不进行跨列
        }
      }
      // 其他列不进行合并
      return {
        rowspan: 1,
        colspan: 1
      }
    },
    async getList() {
      this.loading = true
      const res = await getListAPI(this.query)
      if (res.result === 'OK') {
        this.loading = false
        this.list = res.data.content.map(item => {
          // const parentPalletCode = item.parentPalletCode
          const inventoryVos = item.inventoryVos.map(val => {
            return {
              ...val,
              parentPalletCode: item.parentPalletCode,
              parentPalletType: item.parentPalletType,
              lockStatus: item.lockStatus,
              storageCode: item.storageCode,
              storageType: item.storageType
            }
          })
          return {
            ...item,
            inventoryVos
          }
        }).map(item => item.inventoryVos)
          .reduce((acc, current) => acc.concat(current), [])
        this.totalElements = res.data.totalElements
        this.select_table.forEach(item => {
          this.$nextTick(() => {
            this.list.find(obj => {
              if (item.parentPalletCode === obj.parentPalletCode) {
                this.$refs.table.toggleRowSelection(obj, true)
              }
            })
          })
        })
      }
    },
    async getWareHouse() {
      const res = await getWareHouseAPI()
      if (res.result === 'OK') {
        this.options = res.data
      } else {
        return this.$message.warning(res.data)
      }
    },
    toQuery() {
      this.query.current = 1
      this.getList()
    },
    reset() {
      this.select_table = []
      this.user = {
        type: '',
        warehouse: '',
        code: '',
        name: ''
      }
      this.btn = {
        createBtn: false
      }
      this.query = {
        parentPalletCode: '',
        parentPalletType: '',
        quality: '',
        productNo: '',
        wareHouseType: '',
        current: 1,
        size: 10
      }
      this.toQuery()
    },
    handlerChange(selection, row) {
      let a = 0
      selection.forEach(v => {
        if (v.parentPalletCode !== row.parentPalletCode) {
          a++
        }
      })
      if ((a !== 0 && selection.length !== 0) || (a === 0 && selection.length === 0)) {
        this.select_table.forEach((v, index) => {
          if (v.parentPalletCode === row.parentPalletCode) {
            this.select_table.splice(index, 1)
          }
        })
      }
    },
    handlerAll(val) {
      if (val.length === 0) {
        const set2 = new Set(this.list.map(v => v.parentPalletCode))
        const a = this.select_table.map(v => v.parentPalletCode).filter(item => !set2.has(item))
        const b = this.select_table.filter(v => a.includes(v.parentPalletCode))
        this.select_table = b
      }
    },
    updateSelect(val) {
      for (var i = 0; i < val.length; i++) {
        const n = {
          parentPalletCode: val[i].parentPalletCode
        }
        if (this.select_table.length === 0) {
          this.select_table.push(n)
        } else {
          let a = 0
          for (var j = 0; j < this.select_table.length; j++) {
            if (this.select_table[j].parentPalletCode === val[i].parentPalletCode) {
              a++
            }
          }
          if (a < 1) {
            this.select_table.push(n)
          }
        }
      }
    },
    del(row, index) {
      this.select_table.splice(index, 1)
      this.$nextTick(() => {
        this.list.find(obj => {
          if (obj.parentPalletCode === row.parentPalletCode) {
            this.$refs.table.toggleRowSelection(obj, false)
          }
        })
      })
    },
    handlerSizeChange(e) {
      this.query.size = e
      this.query.current = 1
      this.getList()
    },
    handlerCurrentChange(e) {
      this.query.current = e
      this.getList()
    },
    async createReturnOrder() {
      // if (!this.user.code) {
      //   return this.$message.warning('请输入作业人员工号')
      // }
      // if (this.user.code && !this.user.name) {
      //   return this.$message.warning('请输入作业人员姓名')
      // }
      this.btn.createBtn = true
      const submitForm = {
        applicantEmployeeNo: this.user.code,
        applicantName: this.user.name,
        moveTo: this.user.warehouse,
        parentPalletCodeList: this.select_table.map(item => item.parentPalletCode),
        moveWareHouseOrderType: this.user.type
      }
      const res = await createMoveOrderAPI(submitForm)
      console.log(res)
      if (res.result === 'OK') {
        this.btn.createBtn = false
        this.$message.success('创建成功')
        this.$router.push('/moveManagement/moveOrder')
      } else {
        this.btn.createBtn = false
        this.$message.warning(res.data)
      }
    },
    handlerClick() {
      if (this.showQuery === false) {
        this.showQuery = true
      } else {
        this.showQuery = false
      }
    }
  }
}
</script>

<style scoped lang="scss">
.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
}
.arrow-icon {
  font-size: 12px;
  display: inline-block;
  transition: transform 0.3s ease;
}

::v-deep .el-table .warning-row {
  background: rgb(243, 222, 182) !important;
}

::v-deep .el-table__body .warning-row:hover td {
  background-color: #E1C396 !important;
}
</style>
